package com.dyh.quickdemozwei.dyhTp;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;

/**
 * @Author: yhdong
 * @Date: 2021/10/1 14:09
 */
public class DyhQueue<R extends Runnable> extends LinkedBlockingQueue<Runnable> {

    private DyhThreadPool executor;

    public DyhQueue(int capacity) {
        super(capacity);
    }

    /*
     * @return {@code true} if the element was added to this queue, else
     *         {@code false}
    */
    @Override
    public boolean offer(Runnable runnable) {
        if (executor==null)
            throw new RejectedExecutionException("executor is null");
        else {
            int poolSize = this.executor.getPoolSize();
            int submittedCount = this.executor.getSubmittedCount().get();
            int maximumPoolSize = this.executor.getMaximumPoolSize();

            if (submittedCount < poolSize)
                return super.offer(runnable);
            else{
                if ( poolSize < maximumPoolSize)
                    return false; //不进队列
                else
                    return super.offer(runnable);
            }
        }
    }

    public DyhThreadPool getExecutor() {
        return executor;
    }

    public void setExecutor(DyhThreadPool executor) {
        this.executor = executor;
    }
}
